﻿using Kingdee.BOS;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.BusinessEntity.YunZhiJia;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;

namespace LiMinCRMPlugin.InterfaceDocking
{
    /// <summary>
    /// 产品基准价审核插件
    /// </summary>
    /// <remarks>
    /// 功能：产品基准价在审核后自动传到CRM。
    /// 创建人：wzx
    /// 创建日期：2024.3.26
    /// 修改信息（1）：修改人，修改日期，修改内容
    /// </remarks>
    [Description("产品基准价审核同步至CRM")]
    [HotUpdate]
    public class PriceOfProductToCRM : AbstractOperationServicePlugIn
    {
        //OnPreparePropertys 数据加载前，确保需要的属性被加载
        public override void OnPreparePropertys(PreparePropertysEventArgs e)
        {
            base.OnPreparePropertys(e);

            //单据编码
            e.FieldKeys.Add("FBillNo");
            //生效日期
            e.FieldKeys.Add("F_RDLV_TakeDate");
            //库存组织
            e.FieldKeys.Add("F_RDLV_OrgId");


            //物料
            e.FieldKeys.Add("F_RDLV_Material");
            //规格型号
            e.FieldKeys.Add("F_RDLV_Specification");
            //基准价
            e.FieldKeys.Add("F_RDLV_Price");
            //基本单位
            e.FieldKeys.Add("F_RDLV_BaseUnit");
            //销售单位
            e.FieldKeys.Add("F_RDLV_SalesUnit");
            //同步CRM状态
            e.FieldKeys.Add("F_RDLV_FSTATUS");


            //创建人
            e.FieldKeys.Add("F_RDLV_CreatorId_6oq_fg2");
        }
        /// <summary>
        /// 事务结束后事件
        /// </summary>
        /// <param name="e"></param>
        public override void EndOperationTransaction(EndOperationTransactionArgs e)
        {
            base.EndOperationTransaction(e);
            string InvokeType = "";
            if (this.FormOperation.Operation.ToUpper() == "AUDIT")
            {
                InvokeType = "产品基准价审核自动上传CRM";
            }
            else if (this.FormOperation.Operation.ToUpper() == "REUPLOADPRICEOFPRODUCT")
            {
                InvokeType = "产品基准价手工上传CRM";
            }
            //读取全部的单据,for循环,转换成DynamicObject类型
            foreach (DynamicObject entity in e.DataEntitys)
            {
                string FID = entity["ID"].ToString();
                string FBillNo = entity["BillNo"].ToString();
                string UserAccount = "";//用户账号
                DynamicObject User = entity["F_RDLV_CreatorId_6oq_fg2"] as DynamicObject;//用户
                if (User != null)
                {
                    UserAccount = Convert.ToString(User["UserAccount"]);
                }
                DynamicObject StockOrg = entity["F_RDLV_OrgId"] as DynamicObject;//库存组织
                string StockOrgId = "";//库存组织内码
                string StockOrgNo = "";//库存组织编码
                string StockOrgName = "";
                if (StockOrg != null)
                {
                    StockOrgId = Convert.ToString(StockOrg["ID"]);//库存组织内码
                    StockOrgNo = Convert.ToString(StockOrg["Number"]);//库存组织编码
                    StockOrgName = Convert.ToString(StockOrg["Name"]);//库存组织名称
                }
                string TakeDate = Convert.ToString(entity["F_RDLV_TakeDate"]);//生效日期
                

                 DynamicObjectCollection FEntityDetail = entity["FEntity"] as DynamicObjectCollection;//明细 

                List<PriceOfProductModel.detailList> detailList = new List<PriceOfProductModel.detailList>();//明细数据组
                foreach (var item in FEntityDetail)
                {
                    string FENTRTYID = Convert.ToString(item["id"]);
                    string MaterialId = "";//物料内码
                    string MaterialNo = "";//物料编码
                    string MaterialName = "";//物料名称
                    DynamicObject Material = item["F_RDLV_Material"] as DynamicObject;//物料
                    if (Material != null)
                    {
                        MaterialId = Convert.ToString(Material["Id"]);
                        MaterialNo = Convert.ToString(Material["Number"]); //物料编码
                        MaterialName = Convert.ToString(Material["Name"]); //物料名称
                    }
                    string Price = Convert.ToString(item["F_RDLV_Price"]);//基准价
                    string Specification = Convert.ToString(item["F_RDLV_Specification"]);//规格型号

                    string SalUnitId = "";//销售单位内码
                    string SalUnitNo = "";//销售单位编码
                    DynamicObject SalUnit = item["F_RDLV_SalesUnit"] as DynamicObject;//销售单位
                    if (SalUnit != null)
                    {
                        SalUnitId = Convert.ToString(SalUnit["Id"]);
                        SalUnitNo = Convert.ToString(SalUnit["Number"]); //销售单位编码
                    }

                    string BaseUnitId = "";//基本单位内码
                    string BaseUnitNo = "";//基本单位编码
                    DynamicObject BaseUnit = item["F_RDLV_BaseUnit"] as DynamicObject;//基本单位
                    if (BaseUnit != null)
                    {
                        BaseUnitId = Convert.ToString(BaseUnit["Id"]);
                        BaseUnitNo = Convert.ToString(BaseUnit["Number"]); //基本单位编码
                    }


                    #region 产品基准价detail数组
                    PriceOfProductModel.operate operate=new PriceOfProductModel.operate();
                    operate.action = "SaveOrUpdate";

                    PriceOfProductModel.dataList dataList = new PriceOfProductModel.dataList();
                    dataList.mxwybm = FENTRTYID; 
                    dataList.cpbm = MaterialNo;
                    dataList.cpmc = MaterialName;
                    dataList.ggxh = Specification;
                    dataList.jbdw = BaseUnitNo;
                    dataList.xsdw = SalUnitNo;
                    dataList.jzj = Price;

                    PriceOfProductModel.detailList detailList1 = new PriceOfProductModel.detailList();
                    detailList1.operate = operate;
                    detailList1.data = dataList;
                    detailList.Add(detailList1);
                    #endregion
                }
                #region 产品基准价mainTable数组
                PriceOfProductModel.mainTableList mainTable = new PriceOfProductModel.mainTableList();
                mainTable.djbm = FBillNo;
                mainTable.sxrq = TakeDate;
                mainTable.kczz = StockOrgNo;
             
                #endregion

                if (this.FormOperation.Operation.ToUpper() == "AUDIT")
                {
                    string resultSearch =CRMSearchPriceOfProduct(FBillNo,UserAccount);
                    //不存在数据，需要新增
                    if (resultSearch == "无结果")
                    {
                        Return resultAdd = CRMAddPriceOfProduct(mainTable, detailList, UserAccount);
                        if (resultAdd.status == "1")
                        {
                            #region 产品基准价写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                            Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                            interfaceLog.FBILLNO = FBillNo;
                            interfaceLog.FBILLID = FID;
                            interfaceLog.FDATE = System.DateTime.Now;
                            interfaceLog.FINTERNAME = "新增产品基准价";
                            interfaceLog.FInvokeType = "";
                            interfaceLog.Ftoken = "";
                            interfaceLog.FSTATUS = "成功";
                            interfaceLog.FRequsetData = "{\"data\":[{\"operationinfo\":{\"operator\":\"kd-jxy\",\"operationDate\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "\",\"operationTime\":\"" + DateTime.Now.ToString("HH:mm:ss") + "\"},\"mainTable\":" + JsonConvert.SerializeObject(mainTable) + ",\"detail1\":" + JsonConvert.SerializeObject(detailList) + "}],\"header\":{\"systemid\":\"kingde\",\"" + DateTime.Now + "\":\"currentTimeTamp \",\"Md5\":\"\"}}";
                            interfaceLog.FReturnData = JsonConvert.SerializeObject(resultAdd.datajson);
                            interfaceLog.FRequest = "{\"data\":[{\"operationinfo\":{\"operator\":\"kd-jxy\",\"operationDate\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "\",\"operationTime\":\"" + DateTime.Now.ToString("HH:mm:ss") + "\"},\"mainTable\":" + JsonConvert.SerializeObject(mainTable) + ",\"detail1\":" + JsonConvert.SerializeObject(detailList) + "}],\"header\":{\"systemid\":\"kingde\",\"" + DateTime.Now + "\":\"currentTimeTamp \",\"Md5\":\"\"}}";
                            interfaceLog.FReturn = JsonConvert.SerializeObject(resultAdd.datajson);
                            string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                            List<string> sqlList = new List<string>();
                            if (!string.IsNullOrEmpty(LogSql))
                            {
                                sqlList.Add(LogSql);
                            }
                            //更新单据
                            string updateSql = string.Format(@"/*dialect*/ update RDLV_t_BenchmarkPrice set F_RDLV_FDATE='{0}',F_RDLV_FSTATUS='{1}' 
                    where FID={2}", interfaceLog.FDATE, interfaceLog.FSTATUS, FID);
                            sqlList.Add(updateSql);
                            DBServiceHelper.ExecuteBatch(this.Context, sqlList);
                            #endregion
                        }
                        else
                        {
                            #region 产品基准价写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                            Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                            interfaceLog.FBILLNO = FBillNo;
                            interfaceLog.FBILLID = FID;
                            interfaceLog.FDATE = System.DateTime.Now;
                            interfaceLog.FINTERNAME = "新增产品基准价";
                            interfaceLog.FInvokeType = "";
                            interfaceLog.Ftoken = "";
                            interfaceLog.FSTATUS = "失败";
                            interfaceLog.FRequsetData = "{\"data\":[{\"operationinfo\":{\"operator\":\"kd-jxy\",\"operationDate\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "\",\"operationTime\":\"" + DateTime.Now.ToString("HH:mm:ss") + "\"},\"mainTable\":" + JsonConvert.SerializeObject(mainTable) + ",\"detail1\":" + JsonConvert.SerializeObject(detailList) + "}],\"header\":{\"systemid\":\"kingde\",\"" + DateTime.Now + "\":\"currentTimeTamp \",\"Md5\":\"\"}}";
                            interfaceLog.FReturnData = JsonConvert.SerializeObject(resultAdd.datajson);
                            interfaceLog.FRequest = "{\"data\":[{\"operationinfo\":{\"operator\":\"kd-jxy\",\"operationDate\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "\",\"operationTime\":\"" + DateTime.Now.ToString("HH:mm:ss") + "\"},\"mainTable\":" + JsonConvert.SerializeObject(mainTable) + ",\"detail1\":" + JsonConvert.SerializeObject(detailList) + "}],\"header\":{\"systemid\":\"kingde\",\"" + DateTime.Now + "\":\"currentTimeTamp \",\"Md5\":\"\"}}";
                            interfaceLog.FReturn = JsonConvert.SerializeObject(resultAdd.datajson);
                            string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                            List<string> sqlList = new List<string>();
                            if (!string.IsNullOrEmpty(LogSql))
                            {
                                sqlList.Add(LogSql);
                            }
                            //更新单据
                            string updateSql = string.Format(@"/*dialect*/ update RDLV_t_BenchmarkPrice set F_RDLV_FDATE='{0}',F_RDLV_FSTATUS='{1}' 
                    where FID={2}", interfaceLog.FDATE, interfaceLog.FSTATUS, FID);
                            sqlList.Add(updateSql);
                            DBServiceHelper.ExecuteBatch(this.Context, sqlList);
                            #endregion
                        }
                    }
                    //存在数据，需要更新
                    else if(resultSearch== FBillNo)
                    {
                        Return resultAUpdate =CRMUpdatePriceOfProduct(mainTable, detailList, UserAccount);
                        if (resultAUpdate.status == "1")
                        {
                            #region 产品基准价写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                            Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                            interfaceLog.FBILLNO = FBillNo;
                            interfaceLog.FBILLID = FID;
                            interfaceLog.FDATE = System.DateTime.Now;
                            interfaceLog.FINTERNAME = "更新产品基准价";
                            interfaceLog.FInvokeType = "";
                            interfaceLog.Ftoken = "";
                            interfaceLog.FSTATUS = "成功";
                            interfaceLog.FRequsetData = "{\"data\":[{\"operationinfo\":{\"operator\":\"kd-jxy\",\"operationDate\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "\",\"operationTime\":\"" + DateTime.Now.ToString("HH:mm:ss") + "\"},\"mainTable\":" + JsonConvert.SerializeObject(mainTable) + ",\"detail1\":" + JsonConvert.SerializeObject(detailList) + "}],\"header\":{\"systemid\":\"kingde\",\"" + DateTime.Now + "\":\"currentTimeTamp \",\"Md5\":\"\"}}";
                            interfaceLog.FReturnData = JsonConvert.SerializeObject(resultAUpdate.datajson);
                            interfaceLog.FRequest = "{\"data\":[{\"operationinfo\":{\"operator\":\"kd-jxy\",\"operationDate\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "\",\"operationTime\":\"" + DateTime.Now.ToString("HH:mm:ss") + "\"},\"mainTable\":" + JsonConvert.SerializeObject(mainTable) + ",\"detail1\":" + JsonConvert.SerializeObject(detailList) + "}],\"header\":{\"systemid\":\"kingde\",\"" + DateTime.Now + "\":\"currentTimeTamp \",\"Md5\":\"\"}}";
                            interfaceLog.FReturn = JsonConvert.SerializeObject(resultAUpdate.datajson);
                            string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                            List<string> sqlList = new List<string>();
                            if (!string.IsNullOrEmpty(LogSql))
                            {
                                sqlList.Add(LogSql);
                            }
                            //更新单据
                            string updateSql = string.Format(@"/*dialect*/ update RDLV_t_BenchmarkPrice set F_RDLV_FDATE='{0}',F_RDLV_FSTATUS='{1}' 
                    where FID={2}", interfaceLog.FDATE, interfaceLog.FSTATUS, FID);
                            sqlList.Add(updateSql);
                            DBServiceHelper.ExecuteBatch(this.Context, sqlList);
                            #endregion
                        }
                        else
                        {
                            #region 产品基准价写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                            Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                            interfaceLog.FBILLNO = FBillNo;
                            interfaceLog.FBILLID = FID;
                            interfaceLog.FDATE = System.DateTime.Now;
                            interfaceLog.FINTERNAME = "更新产品基准价";
                            interfaceLog.FInvokeType = "";
                            interfaceLog.Ftoken = "";
                            interfaceLog.FSTATUS = "失败";
                            interfaceLog.FRequsetData = "{\"data\":[{\"operationinfo\":{\"operator\":\"kd-jxy\",\"operationDate\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "\",\"operationTime\":\"" + DateTime.Now.ToString("HH:mm:ss") + "\"},\"mainTable\":" + JsonConvert.SerializeObject(mainTable) + ",\"detail1\":" + JsonConvert.SerializeObject(detailList) + "}],\"header\":{\"systemid\":\"kingde\",\"" + DateTime.Now + "\":\"currentTimeTamp \",\"Md5\":\"\"}}";
                            interfaceLog.FReturnData = JsonConvert.SerializeObject(resultAUpdate.datajson);
                            interfaceLog.FRequest = "{\"data\":[{\"operationinfo\":{\"operator\":\"kd-jxy\",\"operationDate\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "\",\"operationTime\":\"" + DateTime.Now.ToString("HH:mm:ss") + "\"},\"mainTable\":" + JsonConvert.SerializeObject(mainTable) + ",\"detail1\":" + JsonConvert.SerializeObject(detailList) + "}],\"header\":{\"systemid\":\"kingde\",\"" + DateTime.Now + "\":\"currentTimeTamp \",\"Md5\":\"\"}}";
                            interfaceLog.FReturn = JsonConvert.SerializeObject(resultAUpdate.datajson);
                            string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                            List<string> sqlList = new List<string>();
                            if (!string.IsNullOrEmpty(LogSql))
                            {
                                sqlList.Add(LogSql);
                            }
                            //更新单据
                            string updateSql = string.Format(@"/*dialect*/ update RDLV_t_BenchmarkPrice set F_RDLV_FDATE='{0}',F_RDLV_FSTATUS='{1}' 
                    where FID={2}", interfaceLog.FDATE, interfaceLog.FSTATUS, FID);
                            sqlList.Add(updateSql);
                            DBServiceHelper.ExecuteBatch(this.Context, sqlList);
                            #endregion
                        }
                    }
                    else
                    {
                        #region 产品基准价写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                        Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                        interfaceLog.FBILLNO = FBillNo;
                        interfaceLog.FBILLID = FID;
                        interfaceLog.FDATE = System.DateTime.Now;
                        interfaceLog.FINTERNAME = "更新产品基准价";
                        interfaceLog.FInvokeType = "";
                        interfaceLog.Ftoken = "";
                        interfaceLog.FSTATUS = "失败";
                        interfaceLog.FRequsetData = "{\"data\":[{\"operationinfo\":{\"operator\":\"kd-jxy\",\"operationDate\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "\",\"operationTime\":\"" + DateTime.Now.ToString("HH:mm:ss") + "\"},\"mainTable\":" + JsonConvert.SerializeObject(mainTable) + ",\"detail1\":" + JsonConvert.SerializeObject(detailList) + "}],\"header\":{\"systemid\":\"kingde\",\"" + DateTime.Now + "\":\"currentTimeTamp \",\"Md5\":\"\"}}";
                        interfaceLog.FReturnData = resultSearch;
                        interfaceLog.FRequest = "{\"data\":[{\"operationinfo\":{\"operator\":\"kd-jxy\",\"operationDate\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "\",\"operationTime\":\"" + DateTime.Now.ToString("HH:mm:ss") + "\"},\"mainTable\":" + JsonConvert.SerializeObject(mainTable) + ",\"detail1\":" + JsonConvert.SerializeObject(detailList) + "}],\"header\":{\"systemid\":\"kingde\",\"" + DateTime.Now + "\":\"currentTimeTamp \",\"Md5\":\"\"}}";
                        interfaceLog.FReturn = resultSearch;
                        string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                        List<string> sqlList = new List<string>();
                        if (!string.IsNullOrEmpty(LogSql))
                        {
                            sqlList.Add(LogSql);
                        }
                        //更新单据
                        string updateSql = string.Format(@"/*dialect*/ update RDLV_t_BenchmarkPrice set F_RDLV_FDATE='{0}',F_RDLV_FSTATUS='{1}' 
                    where FID={2}", interfaceLog.FDATE, interfaceLog.FSTATUS, FID);
                        sqlList.Add(updateSql);
                        DBServiceHelper.ExecuteBatch(this.Context, sqlList);
                        #endregion
                    }

                }
                else if (this.FormOperation.Operation.ToUpper() == "DELETE")
                {
                    string resultSearch = CRMSearchPriceOfProduct(FBillNo, UserAccount);
                    //存在数据，需要新增
                    if (resultSearch == FBillNo)
                    {
                        string resultDelete = CRMDeletePriceOfProduct(FBillNo, UserAccount);
                        if (resultDelete == "删除成功")
                        {
                            #region 产品基准价写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                            Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                            interfaceLog.FBILLNO = FBillNo;
                            interfaceLog.FBILLID = FID;
                            interfaceLog.FDATE = System.DateTime.Now;
                            interfaceLog.FINTERNAME = "删除产品基准价";
                            interfaceLog.FInvokeType = "";
                            interfaceLog.Ftoken = "";
                            interfaceLog.FSTATUS = "成功";
                            interfaceLog.FRequsetData = "{\"operationinfo\":{\"operator\":\"kd-jxy\"},\"mainTable\":{\"djbm\":\"" + FBillNo + "\"},\"header\":{\"systemid\":\"kingdee\",\"currentDateTime\":\"" + DateTime.Now + "\",\"Md5\":\"md5OfStr \"}}";
                            interfaceLog.FReturnData = resultDelete;
                            interfaceLog.FRequest = "{\"operationinfo\":{\"operator\":\"kd-jxy\"},\"mainTable\":{\"djbm\":\"" + FBillNo + "\"},\"header\":{\"systemid\":\"kingdee\",\"currentDateTime\":\"" + DateTime.Now + "\",\"Md5\":\"md5OfStr \"}}";
                            interfaceLog.FReturn = resultDelete;
                            string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                            List<string> sqlList = new List<string>();
                            if (!string.IsNullOrEmpty(LogSql))
                            {
                                sqlList.Add(LogSql);
                            }
                            DBServiceHelper.ExecuteBatch(this.Context, sqlList);
                            #endregion
                        }
                        else
                        {
                            #region 产品基准价写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                            Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                            interfaceLog.FBILLNO = FBillNo;
                            interfaceLog.FBILLID = FID;
                            interfaceLog.FDATE = System.DateTime.Now;
                            interfaceLog.FINTERNAME = "删除产品基准价";
                            interfaceLog.FInvokeType = "";
                            interfaceLog.Ftoken = "";
                            interfaceLog.FSTATUS = "失败";
                            interfaceLog.FRequsetData = "{\"operationinfo\":{\"operator\":\"kd-jxy\"},\"mainTable\":{\"djbm\":\"" + FBillNo + "\"},\"header\":{\"systemid\":\"kingdee\",\"currentDateTime\":\"" + DateTime.Now + "\",\"Md5\":\"md5OfStr \"}}";
                            interfaceLog.FReturnData = resultDelete;
                            interfaceLog.FRequest = "{\"operationinfo\":{\"operator\":\"kd-jxy\"},\"mainTable\":{\"djbm\":\"" + FBillNo + "\"},\"header\":{\"systemid\":\"kingdee\",\"currentDateTime\":\"" + DateTime.Now + "\",\"Md5\":\"md5OfStr \"}}";
                            interfaceLog.FReturn = resultDelete;
                            string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                            List<string> sqlList = new List<string>();
                            if (!string.IsNullOrEmpty(LogSql))
                            {
                                sqlList.Add(LogSql);
                            }
                            //更新单据
                            string updateSql = string.Format(@"/*dialect*/ update RDLV_t_BenchmarkPrice set F_RDLV_FDATE='{0}',F_RDLV_FSTATUS='{1}' 
                    where FID={2}", interfaceLog.FDATE, "删除失败", FID);
                            sqlList.Add(updateSql);
                            DBServiceHelper.ExecuteBatch(this.Context, sqlList);
                            #endregion
                            throw new KDBusinessException("", "单据同步删除CRM失败，禁止删除");
                        }
                    }
                }
            }
        }

        /// <summary>
        /// api配置
        /// </summary>
        public DataTable APISetting(string InterfaceName)
        {
            string Sql = string.Format(@"select * from RDLV_t_CRMInterface where F_RDLV_InterfaceName='{0}'", InterfaceName);
            return DBServiceHelper.ExecuteDataSet(this.Context, Sql).Tables[0];
        }


        /// <summary>
        /// CRM新增产品基准价接口
        /// </summary>
        public Return CRMAddPriceOfProduct(PriceOfProductModel.mainTableList mainTable, List<PriceOfProductModel.detailList> detail1,string UserAccount)
        {
            //当前日期
            String currentDate = DateTime.Now.ToString("yyyy-MM-dd");
            //当前时间
            String currentTime = DateTime.Now.ToString("hh:mm:ss");

            string requestUri1 = "http://10.10.17.127:8086/api/cube/restful/interface/saveOrUpdateModeData/create_outbound_order";

            //系统标识
            String systemid = "kingdee";
            //密码
            String d_password = "p@ssw0rd...";
            DataTable dt = APISetting("新增产品基准价");
            if (dt.Rows.Count > 0)
            {
                requestUri1 = Convert.ToString(dt.Rows[0]["F_RDLV_URL"]);
                systemid = Convert.ToString(dt.Rows[0]["F_RDLV_SystemId"]);
                d_password = Convert.ToString(dt.Rows[0]["F_RDLV_Password"]);
            }
            //获取时间戳
            String currentTimeTamp = getTimestamp();
            String md5Source = systemid + d_password + currentTimeTamp;
            String md5OfStr = Md5(md5Source).ToLower();

            Return result = PostToPushNews(requestUri1, systemid, currentTimeTamp, md5OfStr, mainTable, detail1, UserAccount);


            return result;
        }

        /// <summary>
        /// CRM更新产品基准价接口
        /// </summary>
        public Return CRMUpdatePriceOfProduct(PriceOfProductModel.mainTableList mainTable, List<PriceOfProductModel.detailList> detail1, string UserAccount)
        {
            //当前日期
            String currentDate = DateTime.Now.ToString("yyyy-MM-dd");
            //当前时间
            String currentTime = DateTime.Now.ToString("hh:mm:ss");

            string requestUri1 = "http://10.10.17.127:8086/api/cube/restful/interface/saveOrUpdateModeData/update_outbound_order";

            //系统标识
            String systemid = "kingdee";
            //密码
            String d_password = "p@ssw0rd...";
            DataTable dt = APISetting("更新产品基准价");
            if (dt.Rows.Count > 0)
            {
                requestUri1 = Convert.ToString(dt.Rows[0]["F_RDLV_URL"]);
                systemid = Convert.ToString(dt.Rows[0]["F_RDLV_SystemId"]);
                d_password = Convert.ToString(dt.Rows[0]["F_RDLV_Password"]);
            }
            //获取时间戳
            String currentTimeTamp = getTimestamp();
            String md5Source = systemid + d_password + currentTimeTamp;
            String md5OfStr = Md5(md5Source).ToLower();

            Return result = PostToUpdateNews(requestUri1, systemid, currentTimeTamp, md5OfStr, mainTable, detail1,UserAccount);


            return result;
        }




        /// <summary>
        /// CRM查询产品基准价接口
        /// </summary>
        public string CRMSearchPriceOfProduct(string djbm, string UserAccount)
        {
            //当前日期
            String currentDate = DateTime.Now.ToString("yyyy-MM-dd");
            //当前时间
            String currentTime = DateTime.Now.ToString("hh:mm:ss");

            string requestUri1 = "http://10.10.17.127:8086/api/cube/restful/interface/getDataByPK/select_outbound_order";

            //系统标识
            String systemid = "kingdee";
            //密码
            String d_password = "p@ssw0rd...";
            DataTable dt = APISetting("查询产品基准价");
            if (dt.Rows.Count >0)
            {
                requestUri1 = Convert.ToString(dt.Rows[0]["F_RDLV_URL"]);
                systemid = Convert.ToString(dt.Rows[0]["F_RDLV_SystemId"]);
                d_password = Convert.ToString(dt.Rows[0]["F_RDLV_Password"]);
            }
            //获取时间戳
            String currentTimeTamp = getTimestamp();
            String md5Source = systemid + d_password + currentTimeTamp;
            String md5OfStr = Md5(md5Source).ToLower();

            string result = PostToSearchNews(requestUri1, systemid, currentTimeTamp, md5OfStr, djbm,UserAccount);


            return result;
        }

        /// <summary>
        /// CRM删除产品基准价接口
        /// </summary>
        public string CRMDeletePriceOfProduct(string djbm, string UserAccount)
        {
            //当前日期
            String currentDate = DateTime.Now.ToString("yyyy-MM-dd");
            //当前时间
            String currentTime = DateTime.Now.ToString("hh:mm:ss");

            string requestUri1 = "http://10.10.17.127:8086/api/cube/restful/interface/deleteModeDataByPK/delete_outbound_order";

            //系统标识
            String systemid = "kingdee";
            //密码
            String d_password = "p@ssw0rd...";
            DataTable dt = APISetting("删除产品基准价");
            if (dt.Rows.Count > 0)
            {
                requestUri1 = Convert.ToString(dt.Rows[0]["F_RDLV_URL"]);
                systemid = Convert.ToString(dt.Rows[0]["F_RDLV_SystemId"]);
                d_password = Convert.ToString(dt.Rows[0]["F_RDLV_Password"]);
            }
            //获取时间戳
            String currentTimeTamp = getTimestamp();
            String md5Source = systemid + d_password + currentTimeTamp;
            String md5OfStr = Md5(md5Source).ToLower();

            string result = PostToDeleteNews(requestUri1, systemid, currentTimeTamp, md5OfStr, djbm, UserAccount);


            return result;
        }

        /// <summary>
        /// md5加密
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static String Md5(string s)
        {
            char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(s);
            byte[] result = md5.ComputeHash(inputBytes);
            int j = result.Length;
            char[] str = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++)
            {
                byte byte0 = result[i];
                str[k++] = hexDigits[byte0 >> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        }

        /// <summary>
        /// CRM查询产品基准价POST
        /// </summary>
        public static string PostToSearchNews(string url, string systemid, string currentTimeTamp, string md5OfStr, string djbm, string UserAccount)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>
            {
                {"datajson","{\"operationinfo\":{\"operator\":\""+UserAccount+"\"},\"mainTable\":{\"djbm\":\""+djbm+"\"},\"header\":{\"systemid\":\""+systemid+"\",\"currentDateTime\":\""+currentTimeTamp+"\",\"Md5\":\""+md5OfStr+"\"}}"}
            };
            string result = string.Empty;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
            #region 添加Post 参数
            StringBuilder builder = new StringBuilder();
            int i = 0;
            foreach (var item in dic)
            {
                if (i > 0)
                    builder.Append("&");
                builder.AppendFormat("{0}={1}", item.Key, item.Value);
                i++;
            }
            byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            #endregion

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            //string[] resAry = result.Split(new string[] { "result" }, StringSplitOptions.None);
            //string json = resAry[resAry.Length - 1].Remove(0, 3);
            //json = Regex.Replace(json, "\"\"", "\"");
            //json = json.Remove(json.Length - 2, 2);
            //json = Regex.Unescape(json);
            //if (json == "{}")
            //{
            //    return "无结果";
            //}
            //else
            //{
            //    Dictionary<string, object> dicJson = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
            //    Dictionary<string, object> mainTableJson = JsonConvert.DeserializeObject<Dictionary<string, object>>(dicJson["mainTable"].ToString());
            //    string returnCode = mainTableJson["djbm"].ToString();
            //    return returnCode;
            //}
            JObject jo = (JObject)JsonConvert.DeserializeObject(result);
            if (jo == null)
            {
                return "无结果";
            }
            else if (jo.ToString().Contains("status"))
            {
                string returnCode = jo["info"].ToString();
                return returnCode;
            }
            else if (jo["result"].ToString() == "{}")
            {
                return "无结果";
            }
            else
            {

                JToken rtToken = jo.SelectToken("result");
                JObject rt = (JObject)JsonConvert.DeserializeObject(rtToken.ToString());
                JToken mtToken = rt.SelectToken("mainTable");
                JObject mt = (JObject)JsonConvert.DeserializeObject(mtToken.ToString());
                string returnCode = mt["djbm"].ToString();
                return returnCode;
            }
        }



        /// <summary>
        /// CRM新增产品基准价POST
        /// </summary>
        public static Return PostToPushNews(string url, string systemid, string currentTimeTamp, string md5OfStr, PriceOfProductModel.mainTableList mainTable, List<PriceOfProductModel.detailList> detail1, string UserAccount)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>
            {
                {"datajson","{\"data\":[{\"operationinfo\":{\"operator\":\""+UserAccount+"\",\"operationDate\":\""+DateTime.Now.ToString("yyyy-MM-dd")+"\",\"operationTime\":\""+DateTime.Now.ToString("HH:mm:ss")+"\"},\"mainTable\":"+JsonConvert.SerializeObject(mainTable)+",\"detail1\":"+JsonConvert.SerializeObject(detail1)+"}],\"header\":{\"systemid\":\""+systemid+"\",\"currentDateTime\":\""+currentTimeTamp+"\",\"Md5\":\""+md5OfStr+"\"}}"}
            };
            string result = string.Empty;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
            #region 添加Post 参数
            StringBuilder builder = new StringBuilder();
            int i = 0;
            foreach (var item in dic)
            {
                if (i > 0)
                    builder.Append("&");
                builder.AppendFormat("{0}={1}", item.Key, item.Value);
                i++;
            }
            byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            #endregion

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            Return @return = new Return();
            //string[] sArray = result.Split(new string[] { "}}\",\"status\":\"", "}]" }, StringSplitOptions.None);
            string[] resAry = result.Split(new string[] { "status" }, StringSplitOptions.None);
            string[] json = result.Split(new string[] { "datajson" }, StringSplitOptions.None);
            //if (resAry[resAry.Length - 1].IndexOf("1") > -1)
            //{
            string status = "";
            status = resAry[resAry.Length - 1].Replace("\"", "");
            status = status.Replace(":", "");
            status = status.Replace("}", "");
            string json1 = json[json.Length - 1].Remove(0, 3);
            json1 = Regex.Replace(json1, "\"\"", "\"");
            json1 = json1.Remove(json1.Length - 2, 2);
            json1 = Regex.Unescape(json1);
            json1 = Regex.Unescape(json1);
            //}
            @return.status = status;
            @return.datajson = json1;
            return @return;
        }



        /// <summary>
        /// CRM更新产品基准价POST
        /// </summary>
        public static Return PostToUpdateNews(string url, string systemid, string currentTimeTamp, string md5OfStr, PriceOfProductModel.mainTableList mainTable, List<PriceOfProductModel.detailList> detail1, string UserAccount)
        {

            Dictionary<string, string> dic = new Dictionary<string, string>
            {
                {"datajson","{\"data\":[{\"operationinfo\":{\"operationDate\":\""+DateTime.Now.ToString("yyyy-MM-dd")+"\",\"operator\":\""+UserAccount+"\",\"operationTime\":\""+DateTime.Now.ToString("HH:mm:ss")+"\"},\"mainTable\":"+JsonConvert.SerializeObject(mainTable)+",\"detail1\":"+JsonConvert.SerializeObject(detail1)+"}],\"header\":{\"systemid\":\""+systemid+"\",\"currentDateTime\":\""+currentTimeTamp+"\",\"Md5\":\""+md5OfStr+"\"}}"}
            };
            string result = string.Empty;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
            #region 添加Post 参数
            StringBuilder builder = new StringBuilder();
            int i = 0;
            foreach (var item in dic)
            {
                if (i > 0)
                    builder.Append("&");
                builder.AppendFormat("{0}={1}", item.Key, item.Value);
                i++;
            }
            string b = builder.ToString();
            byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            #endregion

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            Return @return = new Return();
            result = Regex.Unescape(result);//去除转义符
            result = Regex.Unescape(result);//去除转义符
            string[] resAry = result.Split(new string[] { "status" }, StringSplitOptions.None);
            string[] json = result.Split(new string[] { "datajson" }, StringSplitOptions.None);
            string status = "";
            status = resAry[resAry.Length - 1].Replace("\"", "");
            status = status.Replace(":", "");
            status = status.Replace("}", "");
            string json1 = json[json.Length - 1].Remove(0, 3);
            json1 = Regex.Replace(json1, "\"\"", "\"");
            json1 = Regex.Unescape(json1);
            //}
            @return.status = status;
            @return.datajson = json1;
            return @return;
        }


        /// <summary>
        /// CRM删除产品基准价POST
        /// </summary>
        public static string PostToDeleteNews(string url, string systemid, string currentTimeTamp, string md5OfStr, string djbm, string UserAccount)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>
            {
                {"datajson","{\"operationinfo\":{\"operator\":\""+UserAccount+"\"},\"mainTable\":{\"djbm\":\""+djbm+"\"},\"header\":{\"systemid\":\""+systemid+"\",\"currentDateTime\":\""+currentTimeTamp+"\",\"Md5\":\""+md5OfStr+"\"}}"}
            };
            string result = string.Empty;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
            #region 添加Post 参数
            StringBuilder builder = new StringBuilder();
            int i = 0;
            foreach (var item in dic)
            {
                if (i > 0)
                    builder.Append("&");
                builder.AppendFormat("{0}={1}", item.Key, item.Value);
                i++;
            }
            byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            #endregion

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            string[] resAry = result.Split(new string[] { "result" }, StringSplitOptions.None);
            string json = resAry[resAry.Length - 1].Remove(0, 3);
            //json = json.Remove(json.Length - 2, 2);
            json = Regex.Unescape(json);
            json = Regex.Replace(json, "\"\"", "\"");
            string[] message = json.Split(new string[] { "message" }, StringSplitOptions.None);

            if (json == "{}")
            {
                return "无结果";
            }
            else
            {

                return message[1].Substring(3, 4);
            }
        }


        /**
       * 获取时间戳   格式如：19990101235959
       * @return
       */
        public static String getTimestamp()
        {

            return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss").Replace("-", "").Replace(":", "").Replace(" ", "").Replace("/", "");
        }


        /**
       * 接口返回值自定义 
       */
        public class Return
        {
            public string status { get; set; }
            public string datajson { get; set; }
        }
    }
}
